package com.atguigu.gulimall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 解决feign远程调用请求头丢失
 * feign会重新发送一个新的请求，不会带上相关请求头信息
 * 通过加入RequestInterceptor配置，在远程调用中获取该拦截器中的相关信息
 */
@Configuration
public class GuliFeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                System.out.println("RequestContextHolder线程。。。"+Thread.currentThread().getId());
                //RequestContextHolder请求上下文，封装了该请求的所有信息
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes!=null){
                    HttpServletRequest request = requestAttributes.getRequest();
                    //同步请求头数据 Cookie
                    template.header("Cookie",request.getHeader("Cookie"));
                }
            }
        };
    }
}
